package com.qiniu.pili.droid.rtcstreaming.demo

import android.util.Base64
import org.json.JSONObject
import java.security.InvalidKeyException
import java.security.NoSuchAlgorithmException
import java.security.SignatureException
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

@Throws(SignatureException::class, NoSuchAlgorithmException::class, InvalidKeyException::class)
fun hmac_sha1(data: String, key: String): ByteArray {
    val signingKey = SecretKeySpec(key.toByteArray(), "HmacSHA1")
    val mac = Mac.getInstance("HmacSHA1")
    mac.init(signingKey)
    return mac.doFinal(data.toByteArray())
}

fun genToken(userId: String, roomName: String): String {
    // 1. 定义房间管理凭证，并对凭证字符做URL安全的Base64编码
    val roomAccess = JSONObject("""
            {
              "user_id": "$userId",
              "version": "2.0",
              "room_name": "$roomName",
              "expire_at": 1528208129,
              "perm": "admin"
            }
        """).toString()
    val encodedRoomAccess = Base64.encodeToString(roomAccess.toByteArray(), Base64.NO_WRAP or Base64.URL_SAFE)

    // 2. 计算HMAC-SHA1签名，并对签名结果做URL安全的Base64编码
    val sign = hmac_sha1(encodedRoomAccess, "XbzAioLQ2j5a5H1J2a1J2JjHFlElsXvRevIeXLY-")
    val encodedSign = Base64.encodeToString(sign, Base64.NO_WRAP or Base64.URL_SAFE)

    // 3. 将AccessKey与以上两者拼接得到房间鉴权
    val accessKey = "2QYIlE9f4tRwV4zFEqCNmvPSDXUHtcpIrw-yvlsd"
    val roomToken = "$accessKey:$encodedSign:$encodedRoomAccess"
    return roomToken
}
